const fs = require('fs');
const path = require('path');
const { logger } = require('../utils/logger');

function wrap(handler) {
  return async (req, res, next) => {
    try {
      await handler(req, res, next);
    } catch (error) {
      next(error);
    }
  };
}

const list = wrap(async (req, res) => {
  const iconDir = path.resolve(__dirname, '../../../../小图标');
  
  if (!fs.existsSync(iconDir)) {
    logger.warn({ iconDir }, 'Icon directory not found');
    return res.json({ icons: [] });
  }

  const files = fs.readdirSync(iconDir);
  const icons = files
    .filter((file) => /\.(png|jpg|jpeg|svg|gif|webp)$/i.test(file))
    .map((file) => ({
      name: file,
      url: `/assets/icons/${file}`
    }));

  res.json({ count: icons.length, icons });
});

module.exports = {
  iconsController: {
    list
  }
};
